package com.zm.demo.core;

import org.junit.Test;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
import java.util.concurrent.Executors;

import static java.lang.System.out;

/**
 * Created by Administrator on 2019/7/25.
 */
public class RandomTest {


//    @Test
    public static void  main(String[] args){
        //要求：有A\B\C 三个选项，实现随机取值：A的概率20% B的概率30% C的概率50%

        //初始化包含一百个元素的列表，这里可以是 10个，100个，1000个，越大随机值越真实
        //设置长度确保 1% 至 100% 每一个值都存在
        List<String> strings = new ArrayList<>(100);
        for (int i = 0; i < 100; i++) {
            if (i <20){
                strings.add("A");
            }else if (i<50){
                strings.add("B");
            }else {
                strings.add("C");
            }
        }
        out.println("乱序前：" + strings.toString());
        Collections.shuffle(strings);//打乱顺序，随机性更强
        out.println("乱序后：" + strings.toString());

        Random random = new Random();
        Scanner sc = new Scanner(System.in);
        int n = 0;
        while (n > -1){
            out.println("请输入随机次数：");
            n = sc.nextInt();
            if (n == -1){
                System.exit(0);
            }
            out.println("随机次数=" + n);
            int ACount = 0;
            int BCount = 0;
            int CCount = 0;
            for (int i = 0; i < n; i++) {
                int index = random.nextInt(100);//随机取数区间[0,100)
                if (strings.get(index).equals("A")){//随机到A值
                    ACount++;
                }else if (strings.get(index).equals("B")){//随机到B值
                    BCount++;
                }else if (strings.get(index).equals("C")){//随机到C值
                    CCount++;
                }
            }

            //使用BigDecimal计算，可以设置比值的精确度，本例取两位精度
            out.println("A rate = " + BigDecimal.valueOf(Integer.valueOf(ACount).doubleValue()).divide(BigDecimal.valueOf(Integer.valueOf((ACount + BCount + CCount))), 2, RoundingMode.HALF_UP));
            out.println("B rate = " + BigDecimal.valueOf(Integer.valueOf(BCount).doubleValue()).divide(BigDecimal.valueOf(Integer.valueOf((ACount + BCount + CCount))), 2, RoundingMode.HALF_UP));
            out.println("C rate = " + BigDecimal.valueOf(Integer.valueOf(CCount).doubleValue()).divide(BigDecimal.valueOf(Integer.valueOf((ACount + BCount + CCount))), 2, RoundingMode.HALF_UP));
        }
    }

    @Test
    public void test1(){
        Random r = new Random(10);
        for (int i = 0; i < 10 ; i++) {
            Executors.newCachedThreadPool().submit(() ->{
                out.println(Thread.currentThread().getName() + ": " + r.nextInt(10) + " " + r.nextInt(10) + " " + r.nextInt(10));
            });
        }

    }
}
